package no.sogl.domain;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EntityManager;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.TypedQuery;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;

@RooJavaBean
@RooToString
@RooJpaActiveRecord
public class Tag {

	@Size(max = 50)
	@Column(unique = true)
	private String name;

	@OneToMany(cascade = CascadeType.ALL, mappedBy = "tag")
	private Set<PersonTag> personTags = new HashSet<PersonTag>();

	@NotNull
	@Temporal(TemporalType.TIMESTAMP)
	@DateTimeFormat(style = "S-")
	@Column(updatable = false, insertable = true)
	private Date createdAt = new Date();

	public static Tag findTagByNameEquals(String name) {
		if (name == null || name.length() == 0)
			throw new IllegalArgumentException("The name argument is required");
		EntityManager em = Tag.entityManager();
		TypedQuery<Tag> q = em.createQuery(
				"SELECT o FROM Tag AS o WHERE o.name = :name", Tag.class)
				.setMaxResults(1);
		q.setParameter("name", name);
		try {
			return q.getSingleResult();
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}
	
}
